package app.demo.controller;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springleaf.core.mvc.controller.BaseController;

/**
 * 多文件上传
 * @author leaf
 */
@Controller
@RequestMapping("fileUpload")
public class FileUploadAction extends BaseController {
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	public ModelAndView upload(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
//		String path = getRequest().getSession().getServletContext().getRealPath("/");
		String path = "F://upload/";
		if(request instanceof MultipartHttpServletRequest){
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			List<MultipartFile> files = multipartRequest.getFiles("file");
			for (MultipartFile file : files) {
				String newFilePath = path + file.getOriginalFilename();
				OutputStream out = new FileOutputStream(newFilePath);
				IOUtils.copy(file.getInputStream(), out);
				IOUtils.closeQuietly(out);
				log.debug(file.getOriginalFilename() + "   -> 保存完成");
			}
		}
		
		return renderJson("上传成功!");
	}

}
